package com.umessage.system.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umessage.common.annotation.Log;
import com.umessage.common.config.FebsProperies;
import com.umessage.common.controller.BaseController;
import com.umessage.common.domain.ResponseBo;
import com.umessage.common.service.RedisService;
import com.umessage.common.shiro.CustomizedToken;
import com.umessage.common.shiro.LoginType;
import com.umessage.common.util.MD5Util;
import com.umessage.common.util.MD5Utils;
import com.umessage.common.util.vcode.Captcha;
import com.umessage.common.util.vcode.GifCaptcha;
import com.umessage.hotel.util.HotelConstant;
import com.umessage.system.domain.User;
import com.umessage.system.service.UserService;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private FebsProperies febsProperies;

    @Autowired
    private UserService userService;
    @Autowired
	private RedisService redisService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseBo login(String username, String password, String code, Boolean rememberMe, String mobile, String type) {
        if (!StringUtils.isNotBlank(code)) {
            return ResponseBo.warn("验证码不能为空！");
        }
        //验证码登录
        if(StringUtils.isNotBlank(mobile)){
        	
        	String key = HotelConstant.VERCODE_PREFIX + "_" + type + "_" + mobile;
        	String redisCode = redisService.get(key);
        	if (!code.toLowerCase().equals(redisCode)) {
        		return ResponseBo.warn("验证码错误！");
        	}
        	User user = userService.findUserByMobileNum(mobile);
        	username  = user.getUsername();
            password  = user.getPassword();
        	rememberMe = true;
        }else{
        	/*Session session = super.getSession();
        	String sessionCode = (String) session.getAttribute("_code");
        	session.removeAttribute("_code");*/
        	String sessionCode = redisService.get("username_code"+username);
        	if (!code.toLowerCase().equals(sessionCode)) {
        		return ResponseBo.warn("验证码错误！");
        	}
        	// 密码 MD5 加密
        	password = MD5Utils.encrypt(username.toLowerCase(), password);
//        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        }
        
        CustomizedToken token = new CustomizedToken(username, password, LoginType.SHIRO.toString(), rememberMe);
        try {
            super.login(token);
            this.userService.updateLoginTime(username);
            return ResponseBo.ok();
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResponseBo.error("账户已禁用，请联系管理员!");
        }
    }
    
    @GetMapping(value = "gifCode")
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
        try {
        	String username=(String) request.getParameter("username");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");

            Captcha captcha = new GifCaptcha(
                    febsProperies.getValidateCode().getWidth(),
                    febsProperies.getValidateCode().getHeight(),
                    febsProperies.getValidateCode().getLength());
            captcha.out(response.getOutputStream());
           /* session.removeAttribute("_code");
            HttpSession session = request.getSession(true);
            session.setAttribute("_code", captcha.text().toLowerCase());*/
            redisService.del("username_code"+username);
            if(username!=null) {
            	  redisService.set("username_code"+username, captcha.text().toLowerCase());
            	  redisService.pexpire("username_code"+username, 1000L * 60);// 30s内有效
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @GetMapping("/403")
    public String forbid() {
        return "403";
    }

    @Log("访问系统")
    @RequestMapping("/index")
    @RequiresPermissions("index")
    public String index(Model model) {
        // 登录成后，即可通过 Subject 获取登录的用户信息
        User user = super.getCurrentUser();
        model.addAttribute("user", user);
        return "index";
    }
}
